<script setup>

import CardBox from "@/components/CardBox/index.vue";
import {useRouter} from "vue-router";
import {Download} from "@element-plus/icons-vue";
import {
  getStudentListApi,
  getTeacherListApi,
  detailsScientificProjectsApi,
  getScientificProjectsListApi,
  deleteScientificProjectsApi,
  addScientificProjectsApi,
  updateScientificProjectsApi, wallScientificProjectsApi, downWallScientificProjectsApi,
} from "@/api/school.js";
import useUserStore from "@/store/modules/user.js";
import {formatDateNoTime} from "@/utils/index.js";

const userStore = useUserStore()

const router = useRouter()

const {proxy} = getCurrentInstance();

const state = reactive({
  permission: [],
  studentList: [],
  teacherList: [],
  tableData: [],
  formRules: {
    acTime: [
      {required: true, message: '请选择时间', trigger: 'change'},
    ],
    stuId: [
      {required: true, message: '请选择学生', trigger: 'change'},
    ],
    acTitle: [
      {required: true, message: '请输入名称', trigger: 'blur'},
    ],
    teacherIds: [
      {required: true, message: '请选择指导教师', trigger: 'change'},
    ],
    acDanwei: [
      {required: true, message: '请输入单位', trigger: 'blur'},
    ],
  },

  editForm: {
    id: '',
    stuId: '',
    acTitle: '',
    acFile: '',
  },
  editForm2: {
    id: '',
    stuId: '',
    acTitle: '',
    acFile: '',
  },
  achievementTypeList: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  total: 0,
  title: '新增项目、软著',
  ids: [],
})

const showDia1 = ref(false)
const showDia2 = ref(false)
const selectable = (row) => ![].includes(row.id)
const handleAdd = () => {
  showDia1.value = true
}

const handleUploadSuccess = (response, file, fileList) => {
  console.log(response, file, fileList)
}

const handleEdit = async (id) => {
  // 获取详情
  const res = await detailsScientificProjectsApi({id})
  if (res.code == 200) {
    state.editForm = res.data
    await changeStu(state.editForm.stuId)
    showDia1.value = true
    state.title = '编辑大创科研项目'
  }
}

const getDataList = async () => {
  state.queryParams.acTime = formatDateNoTime(state.queryParams.acTime)
  const res = await getScientificProjectsListApi(state.queryParams)
  if (res.code == 200) {
    state.tableData = res.rows
    state.total = res.total
  }
}

const searchStudent = async (query) => {
  const res = await getStudentListApi({stuName: query})
  if (res.code == 200) {
    state.studentList = res.data
  }
}

const handleDelete = (id) => {
  proxy.$modal.confirm('是否删除该数据？').then(async () => {
    const res = await deleteScientificProjectsApi({id})
    if (res.code == 200) {
      proxy.$modal.msgSuccess("删除成功")
    }
    await getDataList()
  })
}

const handleClose = () => {
  showDia1.value = false
  state.editForm = {
    id: '',
    stuId: '',
    acTitle: '',
  }
  proxy.resetForm("formRef");
  state.title = '新增项目、软著'
}

const getIsStudent = () => {
  return userStore.roles.includes('student')
}

const submitForm = () => {
  proxy.$refs["formRef"].validate(async (valid) => {
    if (valid) {
      let res = ''
      if (state.editForm.id == '') {
        res = await addScientificProjectsApi(state.editForm)
      } else {
        res = await updateScientificProjectsApi(state.editForm)
      }

      if (res.code == 200) {
        proxy.$message.success('操作成功')
        handleClose()
        await getDataList()
      }
    }
  })
}

const resetSearch = () => {
  proxy.resetForm("queryRef");
  state.queryParams = {
    pageNum: 1,
    pageSize: 10,
  }
  getDataList()
}


const getStudentList = async () => {
  const res = await getStudentListApi()
  if (res.code == 200) {
    state.studentList = res.data
  }
}

const handleWall = () => {
  if (state.ids.length == 0) {
    proxy.$modal.msgError("请选择要操作的数据")
  } else {
    proxy.$modal.confirm('是否上墙该数据？').then(async () => {
      const res = await wallScientificProjectsApi({ids: state.ids})
      if (res.code == 200) {
        proxy.$modal.msgSuccess("操作成功")
        await getDataList()
      }
    })
  }
}

const handleDownWall = () => {
  if (state.ids.length == 0) {
    proxy.$modal.msgError("请选择要操作的数据")
  } else {
    proxy.$modal.confirm('是否上墙该数据？').then(async () => {
      const res = await downWallScientificProjectsApi({ids: state.ids})
      if (res.code == 200) {
        proxy.$modal.msgSuccess("操作成功")
        await getDataList()
      }
    })
  }
}


const handleChecked = (id, checked) => {
  const index = state.ids.findIndex(item => item.id === id)
  if (index !== -1) {
    state.ids.splice(index, 1)
  } else {
    state.ids.push(id)
  }
}

const handleApproval = () => {
  router.push("/approvalManagement/teacherApproval")
}

const changeStu = async (id) => {
  state.editForm.instructorTeacherId = ''
  // 获取教师列表
  const res = await getTeacherListApi({id})
  if (res.code == 200) {
    state.teacherList = res.data
  }
}

// 参与项目、软著
const handleJoin = (outPutId) => {
  router.push({
    path: "scientificProjectsJoin",
    query: {
      outPutId
    }
  })
}

const handleExport = async (item) => {
  proxy.download("/school/scientificProjects/export-word", {
    id: item.id
  }, `${item.stuName}科研项目情况.docx`);
}

// 获取当前老师的权限信息
const getPermission = async () => {
  state.permission = userStore.roles
  if (state.permission.includes('teacher')) {
    state.queryParams.teacherType = 0
  } else {
    state.queryParams.teacherType = 1
  }
}

const handleExport2 = async () => {
  proxy.download("/school/scientificProjects/export-word2", {
    ids: state.ids
  }, `科研项目批量导出${new Date().getTime()}.docx`);
}

const handleSelectionChange = (val) => {
  state.ids = val.map(item => item.id)
}

onMounted(() => {
  getDataList()
  getPermission()
  getStudentList()
})

</script>

<template>
  <div class="outBox">
    <CardBox style="margin-bottom: 20px" title="筛选查询">
      <template #btn-cont>
        <el-button type="primary" @click="getDataList">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </template>
      <template #content>
        <el-form :model="state.queryParams" label-width="120" inline="true" ref="queryRef">
          <el-row>
            <el-col :span="5">
              <el-form-item label="结项/结题时间">
                <el-date-picker
                    v-model="state.queryParams.acTime"
                    type="date"
                    placeholder="请选择"
                />

              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="项目来源/类型">
                <el-input v-model="state.queryParams.inputValue1" placeholder="请输入"/>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="项目/课题名称">
                <el-input v-model="state.queryParams.acTitle" placeholder="请输入"/>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="项目课程/编号">
                <el-input v-model="state.queryParams.acDanwei" placeholder="请输入"/>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="主持人">
                <el-input v-model="state.queryParams.stuName" placeholder="请输入"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5">
              <el-form-item label="审核结果">
                <el-select v-model="state.queryParams.acAudit" placeholder="请选择">
                  <el-option label="待审核" value="1"/>
                  <el-option label="通过" value="2"/>
                  <el-option label="拒绝" value="3"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="是否上墙">
                <el-select v-model="state.queryParams.acWall" placeholder="请选择">
                  <el-option label="是" value="2"/>
                  <el-option label="否" value="1"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </CardBox>
    <CardBox title="数据列表">
      <template #btn-cont v-if="!getIsStudent()">
        <!--        <el-button type="primary" @click="handleWall">上墙</el-button>-->
        <!--        <el-button type="primary" @click="handleDownWall">下墙</el-button>-->
        <!--        <el-button type="primary" @click="handleApproval">项目审核</el-button>-->
        <!--        <el-button type="primary" @click="handleAdd">上传项目</el-button>-->
        <el-select v-model="state.queryParams.teacherType" placeholder="请选择" @change="getDataList"
                   v-if="!state.permission.includes('superManager') && !state.permission.includes('admin')"
                   style="width: 150px;margin-right: 15px">
          <el-option label="学业导师" :value="0" v-if="state.permission.includes('teacher')"/>
          <el-option label="专业教师" :value="1" v-if="state.permission.includes('teacher2')"/>
          <el-option label="中队长" :value="3" v-if="state.permission.includes('duizhang')"/>
        </el-select>
        <el-button type="primary" @click="handleExport2">导出</el-button>
      </template>
      <template #content>
        <el-table :data="state.tableData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" :selectable="selectable">
<!--            <template #default="scope">-->
<!--              <el-checkbox v-model="scope.row.checked" @change="handleChecked(scope.row.id, scope.row.checked)"/>-->
<!--            </template>-->
          </el-table-column>
          <el-table-column label="序号" type="index" width="50" align="center"/>
          <el-table-column prop="acTime" label="结项/结题时间" align="center">
            <template #default="scope">
              {{ formatDateNoTime(scope.row.acTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="inputValue1" label="项目来源/类型" align="center"/>
          <el-table-column prop="acTitle" label="项目/课程名称" align="center" width="200">
            <template #default="scope">
              <el-tooltip
                  class="box-item"
                  effect="dark"
                  :content="scope.row.acTitle"
                  placement="top"
              >
                <div>{{ scope.row.acTitle.substring(0, 10) }}</div>
              </el-tooltip>

            </template>
          </el-table-column>
          <el-table-column prop="acDanwei" label="项目/课题编号" align="center"/>
          <el-table-column prop="stuName" label="主持人" align="center"/>
          <el-table-column prop="" label="团队成员" align="center">
            <template #default="scope">
              <span style="margin-right: 5px" v-for="(item,index) in scope.row.participants">{{ item.stuName }} <span
                  v-if="index != scope.row.participants.length - 1">、</span></span>
            </template>
          </el-table-column>
          <el-table-column prop="acDanwei" label="批准单位" align="center"/>
          <el-table-column prop="teachers" label="指导老师" align="center">
            <template #default="scope">
              <el-tag style="margin-right: 5px" v-for="item in scope.row.teachers">{{ item.teacherName }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" link @click="handleEdit(scope.row.id)">项目详情</el-button>
              <!--              <el-button type="primary" size="small" link @click="handleJoin(scope.row.id)">成员详情</el-button>-->
              <el-button type="primary" size="small" link @click="handleExport(scope.row)">导出</el-button>
              <el-button type="danger" size="small" link @click="handleDelete(scope.row.id)" v-if="state.queryParams.teacherType !== 3">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pageBox">
          <pagination
              v-show="state.total > 0"
              :total="state.total"
              v-model:page="state.queryParams.pageNum"
              v-model:limit="state.queryParams.pageSize"
              @pagination="getDataList()"
          />
        </div>
      </template>
    </CardBox>

    <el-dialog :title="state.title" v-model="showDia1" width="800" align-center>
      <div>
        <el-form label-width="120px" ref="formRef" :model="state.editForm" :rules="state.formRules">
          <el-row>
            <el-col :span="24">
              <el-form-item label="授权时间" prop="acTime">
                <el-date-picker
                    v-model="state.editForm.acTime"
                    type="date"
                    placeholder="选择日期"
                    style="width: 200px;"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="参与人" prop="stuId">
                <el-select v-model="state.editForm.stuId"
                           placeholder="请选择"
                           style="width: 200px;"
                           filterable
                           remote
                           reserve-keyword
                           @change="changeStu"
                           :remote-method="searchStudent">
                  <el-option v-for="item in state.studentList" :key="item.id"
                             :label="`${item.stuClass}-${item.stuName}`" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="名称" prop="acTitle">
                <el-input v-model="state.editForm.acTitle"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目号" prop="acDanwei">
                <el-input v-model="state.editForm.acDanwei"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="指导教师" prop="teacherIds">
                <el-select
                    v-model="state.editForm.teacherIds"
                    multiple
                    placeholder="请选择"
                    style="width: 240px"
                    :multiple-limit="3"
                >
                  <el-option
                      v-for="item in state.teacherList"
                      :key="item.id"
                      :label="item.teacherName"
                      :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-form label-width="150" label-position="top">
          <el-form-item label="上传图片/视频/文档：" label-position="top" label-width="150">
            <div class="uploadBox">
              <FileUpload
                  :multiple="false"
                  :limit="1"
                  v-model="state.editForm.acFile"
              />
            </div>
          </el-form-item>
        </el-form>

        <div class="footer">
          <el-button @click="handleClose">返回</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.uploadBox {
  margin-left: 50px;
}

.footer {
  text-align: center;
}
</style>
